import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import Layout from '@/layout/Layout.vue'
import { getLocal } from '@/lib/utils'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'layout',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        name: 'home',
        component: HomeView,
      },
      {
        path: 'userManage',
        name: 'userManage',
        component: () => import('@/views/userManage/index.vue'),
      },
      {
        path: 'fileSystem',
        name: 'fileSystem',
        component: () => import('@/views/fileSystem/index.vue'),
      },
      {
        path: 'stock',
        name: 'stock',
        component: () => import('@/views/stock/index.vue'),
      },
      {
        path: 'article',
        name: 'article',
        component: () => import('@/views/article/index.vue'),
      },
      {
        path: 'videoPlay',
        name: 'videoPlay',
        component: () => import('@/views/videoPlay/videoPlay.vue'),
      },
      {
        path: 'livePlay',
        name: 'livePlay',
        component: () => import('@/views/livePlay/livePlay.vue'),
      },
    ],
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue'),
  },
  {
    path: '/digitalTwin',
    name: 'digitalTwin',
    component: () => import('../views/digitalTwin/digitalTwin.vue'),
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior() {
    return { top: 0 }
  },
})

router.beforeEach(async (to, from, next) => {
  if (to.name === 'login') {
    next()
  } else {
    const token = getLocal('token')
    if (token) {
      next()
    } else {
      next({ name: 'login' })
    }
  }
})

export default router
